package machine.utils;

import machine.bean.Person;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 消息统计工具
 *
 * @author zhanghui145
 * @date 2021/12/26 15:12
 * @since 1.0.0
 */
public final class StatisticalUtil {

    private StatisticalUtil() {
    }

    private static final Map<String, Person> COUNT = new ConcurrentHashMap<>();

    public static void add(String id, final String name) {
        if (COUNT.containsKey(id)) {
            COUNT.computeIfPresent(id, (k, v) -> {
                v.setCounts(v.getCounts() + 1);
                v.setName(name);
                return v;
            });
        } else {
            COUNT.put(id, Person.builder().qq(id).counts(1).build());
        }
    }

    public static void clear() {
        COUNT.values().forEach(p -> p.setCounts(0));
    }

    public static List<Person> getSort() {
        return new ArrayList<>(COUNT.values()).stream()
                .sorted(Comparator.comparingInt(Person::getCounts).reversed())
                .collect(Collectors.toList());
    }
}
